package com.vogue.supplymall.admin.business.domain.biz.impl;

import com.vogue.supplymall.admin.business.domain.biz.OpenShopBiz;
import com.vogue.supplymall.admin.business.domain.model.AdminCheckLicence;
import com.vogue.supplymall.admin.business.domain.service.AdminCheckLicenceService;
import com.vogue.supplymall.common.domain.dto.admin.LicenceSearchInfo;
import com.vogue.supplymall.common.domain.dto.admin.ShopLicenseCheckInfo;
import com.vogue.supplymall.common.exception.DataNotFindException;
import com.vogue.supplymall.entmanagement.domain.model.LicenceApply;
import com.vogue.supplymall.entmanagement.domain.model.LicenceApplyDetail;
import com.vogue.supplymall.entmanagement.domain.service.LicenceApplyDetailService;
import com.vogue.supplymall.entmanagement.domain.service.LicenceApplyService;
import com.vogue.supplymall.shop.domain.service.ShopService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * The type Open shop biz.
 * 审核店铺业务处理类
 *
 * @aouthor: zhangliang
 * @date: Create in 2018-05-15
 */
@Service("openShopBiz")
public class OpenShopBizImpl implements OpenShopBiz {
    /**
     * The constant log.
     */
    public static final Logger LOGGER_OPENSHOPBIZIMPL = LoggerFactory.getLogger(OpenShopBizImpl.class);
    @Resource
    private ShopService shopService;
    @Resource
    private LicenceApplyService licenceApplyService;
    @Resource
    private LicenceApplyDetailService licenceApplyDetailService;
    @Resource
    private AdminCheckLicenceService adminCheckLicenceService;

    @Override
    public Map<String, Long> getShopStatistics(Long syscodeid) {
        LOGGER_OPENSHOPBIZIMPL.info("getShopStatistics 店铺数量统计查询");
        Map<String, Long> result = new HashMap<>();
        // 店铺总数
        Long notOpenCount = shopService.countBySyscodeid(syscodeid);
        result.put("notOpenCount", notOpenCount);
        // 待审核店铺数量
        Long waitCheckShopCnt = licenceApplyService.countByStatus(syscodeid, 0);
        result.put("waitCheckShopCnt", waitCheckShopCnt);
        // 已开通店铺数量
        Long openedShopCnt = licenceApplyService.countByStatus(syscodeid, 1);
        result.put("openedShopCnt", openedShopCnt);
        // 未通过审核店铺数量
        Long deniedShopCnt = licenceApplyService.countByStatus(syscodeid, 2);
        result.put("deniedShopCnt", deniedShopCnt);
        // 续约&变更店铺数量
        Long renewalShopCnt = licenceApplyService.countByType(syscodeid, 2);
        result.put("renewalShopCnt", renewalShopCnt);
        // 证照过期店铺数量
        Long overduelicenceCnt = licenceApplyService.countByStatus(syscodeid, 3);
        result.put("OverduelicenceCnt", overduelicenceCnt);
        return result;
    }

    @Override
    public Map<String, Object> getLicenseHistory(LicenceSearchInfo searchInfo) {
        LOGGER_OPENSHOPBIZIMPL.info(" getLicenseHistory 查询店铺历史证照 ");
        if (searchInfo.getPages() == 0) {
            return null;
        }
        searchInfo.setStart((searchInfo.getPages() - 1) * searchInfo.getLength());
        // 开通店铺-查询集团申请开通的店铺
        Map<String, Object> data = new HashMap<>();
        List<Map<String, Object>> shopInfo;
        Long totalPages = licenceApplyDetailService.findOverdueLicenceCount(searchInfo);
        data.put("totalPages", totalPages);
        if (totalPages > 0L) {
            shopInfo = licenceApplyDetailService.findOverdueLicence(searchInfo);
            data.put("lists", shopInfo);
        }
        return data;
    }

    @Override
    @Transactional
    public Boolean checkLicence(ShopLicenseCheckInfo checkInfo) {
        LicenceApplyDetail licenceApplyDetail = licenceApplyDetailService.get(checkInfo.getLicenceId());
        if (null == licenceApplyDetail) {
            throw new DataNotFindException("");
        }
        // 如果要审核的状态同数据库一样，则不做任何修改
        if (licenceApplyDetail.getApplystatue() == checkInfo.getCheckStatus()) {
            return true;
        }
        // 设置正在审核的证照状态
        licenceApplyDetail.setApplystatue(checkInfo.getCheckStatus());
        licenceApplyDetail.setModifyDate(new Date());
        licenceApplyDetailService.update(licenceApplyDetail);

        // 检查是否全部审核通过
        List<Map<String, Object>> licences = licenceApplyDetailService.findByApplyId(checkInfo.getApplyId());
        int applyPass = 0;
        int applyNoPass = 0;
        for (Map<String, Object> licence : licences) {
            if ("1".equals(licence.get("applystatue").toString())) {
                applyPass++;
            }
            if ("2".equals(licence.get("applystatue").toString())) {
                applyNoPass++;
            }
        }

        // 三个全通过则申请更新为通过
        if (applyPass >= licences.size()) {
            LicenceApply licenceApply = licenceApplyService.get(checkInfo.getApplyId());
            // 如果续约申请通过，当前为过期，更新续约申请为当前申请
            if (licenceApply.getApplytype() == 2) {
                List<LicenceApply> applys = licenceApplyService
                        .selectByWhr(" shopid = " + checkInfo.getShopId() + " and applytype = 1 and applystatue = 3");
                if (applys.size() > 0) {
                    LicenceApply apply = applys.get(0);
                    apply.setApplytype(0);
                    // 更新当前为历史
                    apply.setModifyDate(new Date());
                    licenceApplyService.update(apply);
                    // 设置续约为当前
                    licenceApply.setApplytype(1);
                }
            }
            licenceApply.setApplystatue(1);
            licenceApply.setCheckdate(new Date());
            licenceApply.setModifyDate(new Date());
            licenceApplyService.update(licenceApply);
            // 如果店铺未开通，更新店铺为开通
//            String sql = " syscodeid = #{syscodeid} and matchid = #{matchid}";
//            Map<String, Object> para = new HashMap<>();
//            para.put("syscodeid", checkInfo.getSyscodeid());
//            para.put("matchid", checkInfo.getMatchid());
//            List<Shop> shops = shopService.selectByWhr0(sql, para);
//            for (Shop shop : shops) {
//                shop.setDisabledflag(false);
//                shop.setModifyDate(new Date());
//                shopService.update(shop);
//            }
//            // 开通集团
//            openOrgan(checkInfo);
            // 如果是当前的申请通过审核，添加一个任务
            if (licenceApply.getApplytype() == 1) {
                // 保存要开通的申请信息
                AdminCheckLicence adminCheckLicence = adminCheckLicenceService.get(licenceApply.getId());
                if (null == adminCheckLicence) {
                    adminCheckLicence = new AdminCheckLicence();
                    adminCheckLicence.setId(licenceApply.getId());
                    adminCheckLicence.setApplyid(licenceApply.getId());
                    adminCheckLicence.setMatchid(licenceApply.getMatchid());
                    adminCheckLicence.setShopid(licenceApply.getShopid());
                    adminCheckLicence.setSyscodeid(licenceApply.getSyscodeid());
                    adminCheckLicence.setOnoff(0);
                    adminCheckLicence.setType(0);
                    adminCheckLicenceService.save(adminCheckLicence);
                } else {
                    adminCheckLicence.setOnoff(0);
                    adminCheckLicence.setDisabledflag(false);
                    adminCheckLicence.setModifyDate(new Date());
                    adminCheckLicenceService.update(adminCheckLicence);
                }
            }
        }

        // 有一个未通过则申请更新为未通过
        if (applyNoPass >= 1) {
            LicenceApply licenceApply = licenceApplyService.get(checkInfo.getApplyId());
            if (licenceApply.getApplystatue() != 2) {
                // 申请记录设置为未通过
                licenceApply.setApplystatue(2);
                licenceApply.setCheckdate(new Date());
                licenceApply.setModifyDate(new Date());
                licenceApplyService.update(licenceApply);
                // 如果是当前的申请未通过审核，并且店铺开通中，更新店铺为关闭
                if (licenceApply.getApplytype() == 1) {
//                    String sql = " syscodeid = #{syscodeid} and matchid = #{matchid}";
//                    Map<String, Object> para = new HashMap<>();
//                    para.put("syscodeid", checkInfo.getSyscodeid());
//                    para.put("matchid", checkInfo.getMatchid());
//                    List<Shop> shops = shopService.selectByWhr0(sql, para);
//                    for (Shop shop : shops) {
//                        shop.setDisabledflag(false);
//                        shop.setModifyDate(new Date());
//                        shopService.update(shop);
//                    }
//                    // 关闭集团
//                    closeOrgan(checkInfo);

                    // 保存要关闭的申请信息
                    AdminCheckLicence adminCheckLicence = adminCheckLicenceService.get(licenceApply.getId());
                    if (null == adminCheckLicence) {
                        adminCheckLicence = new AdminCheckLicence();
                        adminCheckLicence.setId(licenceApply.getId());
                        adminCheckLicence.setApplyid(licenceApply.getId());
                        adminCheckLicence.setMatchid(licenceApply.getMatchid());
                        adminCheckLicence.setShopid(licenceApply.getShopid());
                        adminCheckLicence.setSyscodeid(licenceApply.getSyscodeid());
                        adminCheckLicence.setOnoff(1);
                        adminCheckLicence.setType(0);
                        adminCheckLicenceService.save(adminCheckLicence);
                    } else {
                        adminCheckLicence.setOnoff(1);
                        adminCheckLicence.setDisabledflag(false);
                        adminCheckLicence.setModifyDate(new Date());
                        adminCheckLicenceService.update(adminCheckLicence);
                    }
                }
            }
        }

        return true;
    }

}
